package main

import (
	"context"
	"encoding/json"
	"fmt"
	v2 "git.ouryun.cn/lzj1/grpc-bidirectional-stream/pkg/apis/v2"
	v4 "git.ouryun.cn/lzj1/grpc-bidirectional-stream/pkg/services/v4"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

var r = gin.Default()

func main() {
	//r := gin.Default()

	server := v4.NewGrpcClient("127.0.0.1:10002", context.Background(), Callback)
	go func() {
		if err := server.Start(); err != nil {
			log.Fatalf("server start error: %v", err)
		}
	}()

	r.GET("/user/:id", func(c *gin.Context) {
		s := &struct {
			Id   int    `form:"id" json:"id" binding:"required"`
			Name string `form:"name" json:"name" binding:"required"`
		}{
			Id:   1,
			Name: "test",
		}

		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": s,
		})
	})

	r.POST("/user", func(c *gin.Context) {
		s := &struct {
			Id   int    `form:"id" json:"id" binding:"required"`
			Name string `form:"name" json:"name" binding:"required"`
		}{}
		data, err := c.GetRawData()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    400,
				"message": fmt.Sprintf("Error parsing form: %s", err.Error()),
			})
			return
		}
		json.Unmarshal(data, s)
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": s,
		})
	})

	r.Run(":8081")
}

func Callback(message *v2.StreamMessage) {
	log.Printf("callback: %s", message.String())
	log.Print(message.GetRequest().Url)
	routes := r.Routes()
	for _, route := range routes {
		log.Printf("route: %s", route.Path)
	}

}
